/**
 * 
 */
package org.codesmell.util.rendermap.js;

import java.awt.Color;
import java.lang.reflect.Array;

import org.codesmell.util.rendermap.ValueRenderer;

/**
 * @author Uwe Schäfer, (schaefer@thomas-daily.de)
 */
public class JSValueRenderer implements ValueRenderer
{
    private static final long serialVersionUID = 1L;

    @Override
    public String render(final Object value)
    {
        if (value == null)
        {
            return null;
        }
        if ((value instanceof Number) || (value instanceof Boolean))
        {
            return value.toString();
        }

        if (value instanceof Color)
        {
            final Color c = (Color) value;
            return render(toRGBHex(c));
        }

        if (value.getClass().isArray())
        {
            final Class<?> ct = value.getClass().getComponentType();
            Object[] sa = null;
            if (ct.isPrimitive())
            {
                sa = convertPrimitiveArray(value);
            }
            else
            {
                sa = (Object[]) value;
            }

            if (sa.length == 1)
            {
                return render(sa[0]);
            }

            final StringBuffer sb = new StringBuffer(32);
            sb.append("[");
            for (int i = 0; i < sa.length; i++)
            {
                if (i > 0)
                {
                    sb.append(",");
                }
                final Object s = sa[i];
                sb.append(render(s));
            }
            sb.append("]");

            return sb.toString();
        }
        return "'" + escaped(value.toString() + "'");
    }

    private static String escaped(final String value)
    {
        return value.replaceAll("'", "\\'");
    }

    public static Object[] convertPrimitiveArray(final Object array)
    {
        // don´t do this at home
        final int arrayLength = Array.getLength(array);

        final Object[] result = (Object[]) Array.newInstance(Object.class, arrayLength);
        for (int i = 0; i < arrayLength; i++)
        {
            Array.set(result, i, Array.get(array, i));
        }
        return result;
    }

    public static String toRGBHex(final Color c)
    {
        return "#" + twoDigitHex(c.getRed()) + twoDigitHex(c.getGreen()) + twoDigitHex(c.getBlue());
    }

    private static String twoDigitHex(final int colorChannel)
    {
        String s = Integer.toHexString(colorChannel);
        if (s.length() == 1)
        {
            s = "0" + s;
        }
        return s;
    }
}
